package cn.thread.pool.dynamic.thread.pool.sdk.trigger.listen;

import cn.thread.pool.dynamic.thread.pool.sdk.domain.IDynamicThreadPoolService;
import cn.thread.pool.dynamic.thread.pool.sdk.domain.model.entity.ThreadPoolConfigEntity;
import cn.thread.pool.dynamic.thread.pool.sdk.register.Iregister;
import com.alibaba.fastjson.JSON;
import org.redisson.api.listener.MessageListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;


/**
 * @author: xiaoxie
 * create: 2025-02-12 13:45
 * @BelongsProject: custom-dynamic-thread-pool
 * @BelongsPackage: cn.thread.pool.dynamic.thread.pool.sdk.trigger.listen
 * description: redis监听
 */
public class redisListen implements MessageListener<ThreadPoolConfigEntity> {
    private final Logger logger = LoggerFactory.getLogger(redisListen.class);

    private final IDynamicThreadPoolService service;

    private final Iregister iregister;

    public redisListen(IDynamicThreadPoolService service, Iregister iregister) {
        this.service = service;
        this.iregister = iregister;
    }

    /**
     *  上报数据
     */
    @Override
    public void onMessage(CharSequence charSequence, ThreadPoolConfigEntity threadPoolConfigEntity) {
        logger.info("动态线程池，调整线程池配置。线程池名称:{} 核心线程数:{} 最大线程数:{}", threadPoolConfigEntity.getThreadPoolName(), threadPoolConfigEntity.getCorePoolSize(), threadPoolConfigEntity.getMaximumPoolSize());
        service.updateThreadPoolConfig(threadPoolConfigEntity);
        // 上报线程池
        List<ThreadPoolConfigEntity> threadPoolConfigList = service.queryAllThreadPools();
        iregister.registerThreadPoolList(threadPoolConfigList);
        ThreadPoolConfigEntity threadPoolConfigEntityCurren = service.queryThreadPoolConfigByName(threadPoolConfigEntity.getThreadPoolName());
        iregister.registerThreadPoolConfigParameter(threadPoolConfigEntityCurren);
        logger.info("动态线程池，上报线程池配置：{}", JSON.toJSONString(threadPoolConfigEntity));

    }
}
